package pers.hubb.controller;

import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.hubb.domain.TUserDO;
import pers.hubb.service.ITUserDOService;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j
@RestController
@RequestMapping(value = "/data/jdbc/user")
public class TUserDOController {
	@Autowired
	private ITUserDOService tuserDOService;

	/**
	 * 查询用户列表
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Map<String, Object> getTUserDOList(HttpServletRequest request) {
		List<TUserDO> authorList = this.tuserDOService.findTUserDOList();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("total", authorList.size());
		param.put("rows", authorList);
		return param;
	}

	/**
	 * 查询用户信息
	 */
	@RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
	public TUserDO getTUserDO(@PathVariable Long userId, HttpServletRequest request) {
		TUserDO author = this.tuserDOService.findTUserDO(userId);
		if (author == null) {
			throw new RuntimeException("查询错误");
		}
		return author;
	}

	/**
	 * 新增方法
	 */
	@RequestMapping(method = RequestMethod.POST)
	public void add(@RequestBody TUserDO user) {
		try {
			this.tuserDOService.add(user);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException("新增错误");
		}
	}

	/**
	 * 更新方法
	 */
	@RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
	public void update(@PathVariable Long userId, @RequestBody TUserDO user) {
		TUserDO author = this.tuserDOService.findTUserDO(userId);
		author.setRealName(user.getRealName());
		author.setNickName(user.getNickName());
		try {
			this.tuserDOService.update(author);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException("更新错误");
		}
	}

	/**
	 * 删除方法
	 */
	@RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
	public void delete(@PathVariable Long userId) {
		try {
			this.tuserDOService.delete(userId);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException("删除错误");
		}
	}
}
